/**
 * Created by crazycooler on 2018/5/2.
 */
import React,{Component} from 'react'
import {Form,Input,Button} from 'antd'

//util
import WtHostPost from '../util/WtHostPost'
import WtNotification from '../util/WtNotification'
import WtLogger from '../util/WtLogger'
import WtFormLayout from '../util/WtFormLayout'
import WtDefaultHandlePostError from '../util/WtDefaultHandlePostError'
import {ACTION_AUTH, ACTION_NOTIFY} from "../store/action";
import {connect} from "react-redux";

//const
const FormItem = Form.Item;


class WtChangePasswordForm extends Component{
	constructor(props){
		super(props);
		this.state = {
			confirmDirty:false,
		};
	}

	handleSubmit = (e) => {
		e.preventDefault();
		this.props.form.validateFields((err, values) => {
			if (!err) {
                WtLogger.log('Received values of form: ', values);
                if(!values.newPassword.trim().length){
                    WtNotification.error('请输入规范密码');
                    return;
                }
				const {onFinish} = this.props;
				if(onFinish){
					onFinish(values);
				}
			}
		});
	};
	handleConfirmBlur = (e) => {
		const value = e.target.value;
		this.setState({ confirmDirty: this.state.confirmDirty || !!value });
	};


    //和上一个密码（新密码）比较两次是否相同
	compareToFirstPassword = (rule, value, callback) => {
		const form = this.props.form;
		if (value && value !== form.getFieldValue('newPassword')) {
			callback('新密码两次输入不同!');
		} else {
			callback();
		}
	};

    //和下一个密码（再次输入密码）比较两次是否相同
	validateToNextPassword = (rule, value, callback) => {
		const form = this.props.form;
		if (value && this.state.confirmDirty) {
			form.validateFields(['confirm'], { force: true });
		}
		callback();
	};

	render(){
		const { getFieldDecorator } = this.props.form;
		return (
			<Form onSubmit={this.handleSubmit}>
				<FormItem
					{...WtFormLayout.formItemLayout}
					label="旧密码"
				>
					{getFieldDecorator('oldPassword', {
						rules: [{ required: true, message: '请输入旧密码' }],
					})(
						<Input type="password"/>
					)}
				</FormItem>
				<FormItem
					{...WtFormLayout.formItemLayout}
					label="新密码"
				>
					{getFieldDecorator('newPassword', {
						rules: [{ required: true, message: '请输入新密码' },
							{validator: this.validateToNextPassword,}
						],
					})(
						<Input type="password"/>
					)}
				</FormItem>
				<FormItem
					{...WtFormLayout.formItemLayout}
					label="确认密码"
				>
					{getFieldDecorator('confirm', {
						rules: [{ required: true, message: '请输入确认密码' },
						{validator: this.compareToFirstPassword,}
					],
					})(
						<Input type="password" onBlur={this.handleConfirmBlur}/>
					)}
				</FormItem>
				<FormItem {...WtFormLayout.tailFormItemLayout} style={{textAlign:'right'}}>
					<Button loading={this.props.submitting} type="primary" htmlType="submit" style={{width:100,margin:5}}>提交</Button>
				</FormItem>
			</Form>
		);
	}
}

const WtChangePasswordFormWrapper = Form.create()(WtChangePasswordForm);

class WtChangePassword extends Component{
	constructor(props){
		super(props);
		this.state = {
            submitting:false
		}
	}

	onFinish = (values) => {
		this.setState({submitting:true});

		WtHostPost('/changePassword',{
			oldPassword:values.oldPassword,
			newPassword:values.newPassword,
		},true).then(({json,header}) => {
			if(json.code === 0){
				WtNotification.success('修改密码成功');
				this.props.logout();
			}else{
				throw json;
			}
            this.setState({submitting:false});
		}).catch(error => {
			WtNotification.error('修改密码失败');
            this.setState({submitting:false});
		})
	};

	render(){
		return (
			<div style={{margin:'0 50px'}}>
				<h2>修改密码</h2>
				<div style={{marginTop:30}}>
					<WtChangePasswordFormWrapper
						onFinish={this.onFinish}
                        submitting={this.state.submitting}
					/>
				</div>
			</div>
		);
	}
}
const mapDispatchToProps = {
	logout:() => {
		return {
			type:ACTION_AUTH.LOGOUT,
		}
	},
	notifyChange:(count) => {
		return {
			type:ACTION_NOTIFY.CHANGE,
			payload:{
				count,
			}
		}
	}
};

export default connect(null,mapDispatchToProps)(WtChangePassword);
